package 
{
	import alternativa.engine3d.controllers.CameraController;
	import alternativa.engine3d.core.Camera3D;
	import alternativa.engine3d.core.Mesh;
	import alternativa.engine3d.core.Object3D;
	import alternativa.engine3d.core.Scene3D;
	import alternativa.engine3d.display.View;
	import alternativa.engine3d.materials.WireMaterial;
	import alternativa.types.Point3D;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class World3D extends Sprite
	{
		private var _viewWidth: Number;
		private var _viewHeight: Number;
		
		public function World3D( viewWidth: Number = 400, viewHeight: Number = 300 )
		{
			this._viewWidth = viewWidth;
			this._viewHeight = viewHeight;
			createWorld( viewWidth, viewHeight );
		}
		
		public var scene: Scene3D;
		public var view: View;
		public var camera: Camera3D;
		public var cameraController: CameraController;
		
		
		private function createWorld( viewWidth: Number, viewHeight: Number ): void
		{
			this._viewWidth = viewWidth;
			this._viewHeight = viewHeight;
			this.addEventListener( Event.ADDED_TO_STAGE, init );
		}
		
		
		private function init( e: Event ): void
		{
			this.removeEventListener( Event.ADDED_TO_STAGE, init );
			
			scene = new Scene3D();
			scene.root = new Object3D();
			
			camera = new Camera3D();
			scene.root.addChild( camera );
			
			cameraController = new CameraController( stage );
			cameraController.camera = camera;
			
			view = new View();
			view.width = _viewWidth;
			view.height = _viewHeight;
			addChild( view );
			view.camera = camera;
			
			this.addEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
		
		
		private function onEnterFrame( e: Event ): void
		{
			cameraController.processInput();
			scene.calculate();
		}
		
		
		
		public function drawLine( from: Point3D, to: Point3D, lineColor: uint, lineWidth: uint): void 
		{
			var line:Mesh = new Mesh();
			line.createVertex (from.x, from.y, from.z);
			line.createVertex (to.x, to.y, to.z);
			// alternativa needs 3+ vertices per face
			line.createVertex (to.x, to.y, to.z + 1e-9);
			
			line.createFace ( [ 0, 1, 2 ] );
			line.createFace ( [ 2, 1, 0 ]);
			line.moveAllFacesToSurface( 0 );
			line.cloneMaterialToAllSurfaces ( new WireMaterial( lineWidth, lineColor ) );
			scene.root.addChild ( line );
		}
		
	}
}


